<!--聊天界面-->
<script>
import { getUserById } from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { selectMessageRecord } from '@/api/chat/message'
import SocketUtil from '@/utils/SocketUtil'

export default {
  name: '',
  data() {
    return {
      targetUserId: 0,
      targetUserInfo: {},
      chatValue: '',

      socket: null,
      messageText: '',

      mySendMessageList: [],
      toSendMessageList: []

    }
  },
  methods: {
    onBack() {
      this.$router.go(-1)
    },

    //查询聊天记录
    getMessageHistory() {
      console.log()

      let data = {
        receiveUserId: this.targetUserId,
        sendUserId: this.$store.state.user.id
      }
      selectMessageRecord(data).then(({ data }) => {
        this.mySendMessageList = data
      })
    },

    onDetail() {

    },

    getUserInfo() {
      getUserById(this.targetUserId).then(({ data }) => {
        this.targetUserInfo = data
      })
    },

    connect() {
      this.socket = SocketUtil.connect(`/websocket/sendMessage/${this.targetUserId}`, (data) => {
        this.mySendMessageList.push(data)
      })
    },
    onEnterKeyPressed(event) {
      event.preventDefault() // 阻止默认行为（如跳转等）

      this.sendMessage()

      // 同样在发送完成后重新聚焦到搜索框
      this.$refs.searchInput.focus()
    },
    sendMessage() {
      // 向服务器发送消息
      if (this.socket) {
        const messageJson = this.messageText

        console.log('发送的消息,', messageJson)
        this.socket.send(messageJson)
      }
    },

    /**
     * 检查socket是否连接状态,如果没有连接则自动重试连接
     */
    checkConnect() {
      setInterval(() => {
        let flag1 =this.socket.readyState === WebSocket.OPEN
        let flag2 =this.socket.readyState === WebSocket.CONNECTING
        if (!flag1) {
          console.log('socket 没有连接,重试,,,')
          this.connect()
        }
      }, 1000)
    }

  },
  updated() {
    const container = this.$el.querySelector('.chat-container')
    container.scrollTop = container.scrollHeight
  },
  created() {
    this.targetUserId = this.$route.params.userId
    console.log('target user id: ', this.$route.params.userId)
    this.getUserInfo()
    this.connect()
    this.checkConnect()
    this.getMessageHistory()
  },
  beforeDestroy() {
    SocketUtil.disconnect(this.socket)
  }
}
</script>

<template>
  <div>
    <div class="header">
      <van-nav-bar
        :title="targetUserInfo.nickName"
        left-text="返回"
        right-text="详情"
        left-arrow
        @click-left="onBack"
        @click-right="onDetail"
      />

    </div>


    <div class="chatting">
      <div class="chat-container">
        <div v-for="message in mySendMessageList" :key="message.id" class="message">
          <img :src="message.avatar" class="avatar"/>
          <div class="content">{{ message.message }}</div>
        </div>
        <!--        <div v-for="message in toSendMessageList" :key="message.id" class="message">-->
        <!--          <img :src="message.avatar" class="avatar"/>-->
        <!--          <div class="content">{{ message.message }}</div>-->
        <!--        </div>-->
      </div>
    </div>


    <div class="bottom">
      <van-search
        style="width: 100%"
        v-model="messageText"
        maxlength="500"
        show-action
        shape="round"
        :background="'#4fc08d'"
        placeholder="请输入发送的消息"
        @keydown.enter="onEnterKeyPressed"
      >
        <template #action>
          <van-button round size="small" @click="sendMessage" type="info">发送</van-button>
        </template>
      </van-search>
    </div>
  </div>
</template>

<style>
.header {
  //width: 100vh;
  height: 5vh;
  //background-color: #ad9393;
}


.chatting {
  width: 100%;
  height: 89vh;
  background-color: #c3d0f1;
}

.bottom {
  width: 100%;
  height: 6vh;
  background-color: #d8c3f1;
}

.chat-container {
  max-height: 89vh; /* 你可以根据需要调整这个值 */
  overflow-y: auto;
}

.message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.content {
  background-color: #f0f0f0;
  padding: 10px;
  border-radius: 10px;
}
</style>
